package main

import (
	"io"
	"log"
	"net"
	"net-client/encrypt"
	"net-client/msyscall"
	"os"
	"os/signal"
	"syscall"
)

func main() {
	listen, err := net.Listen("tcp", ":1081")
	if err != nil {
		log.Fatalf("listen fail :%s", err)
	}
	msyscall.SetDefaultProxy()
	//注册退出函数 清理设置的代理数据
	clearDefaultProxy()

	log.Println("=============代理客户端启动成功================")
	log.Println("请勿直接退出 退出请按两次ctrl+c !!!!!!!!!!!!!!!!")
	for {
		cConn, err := listen.Accept()
		if err != nil {
			log.Printf("Accept fail: %s", err)
			continue
		}
		go handlerConn(cConn)
	}
}

func clearDefaultProxy() {
	//监听退出序号
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
	go func() {
		sig := <-sigs
		log.Println(sig)
		msyscall.CancelProxy()
		os.Exit(0)
	}()
}

func handlerConn(cConn net.Conn) {
	defer func() {
		if err := recover(); err != nil {
			//fmt.Printf("panic err is %s\n", err)
		}
	}()
	var sConn net.Conn
	var err error
	//proxy.candy-wind.com
	sConn, err = net.Dial("tcp", "proxy.candy-wind.com:8488")
	if err != nil {
		panic(err)
	}
	buffer := make([]byte, 1024)
	rn, err := cConn.Read(buffer)
	if err != nil {
		panic(err)
	}
	aesEncrypt, _ := encrypt.AesEncrypt(buffer[0:rn], encrypt.PrivateKey)
	sConn.Write(aesEncrypt)
	buffer2c := make([]byte, 1024)
	readn, _ := sConn.Read(buffer2c)
	crypt, _ := encrypt.AesDeCrypt(buffer2c[0:readn], encrypt.PrivateKey)
	sConn.Write(crypt)
	go copy2Client(cConn, sConn)
	_, err = io.Copy(sConn, cConn)
	if err != nil {
		//log.Printf("Copy2Server fail: %s", err)
	}
}

func copy2Client(cConn net.Conn, sConn net.Conn) {
	defer func() {
		cConn.Close()
		sConn.Close()
	}()
	_, err := io.Copy(cConn, sConn)
	if err != nil {
		//log.Printf("Copy2Client fail: %s", err)
	}
}
